//
//  LXDepositApplyViewController.m
//  ZuLinProject
//
//  Created by bancheng on 2021/12/24.
//  Copyright © 2021 LX_App. All rights reserved.
//

#import "LXDepositApplyViewController.h"
#import "LXTableViewCell.h"
#import "LXApplyAnnexTableCell.h"
#import "LXChooseBtnTableViewCell.h"
#import "LXRepairModel.h"
#import "LXRemarkTabelViewCell.h"
#import "LXPhotoHelper.h"
#import "LXChooseManagerViewController.h"
#import "FuZeRenModel.h"
#import "LXDepositModel.h"
@interface LXDepositApplyViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic) UITableView *tableView;
@property (nonatomic) NSMutableArray *data;
@property (nonatomic) NSMutableDictionary *loanDic;
@property (nonatomic) NSDictionary *selDic;
@property (nonatomic) CheLiangModel *carModel; // 车辆数据
@property (nonatomic) NSMutableArray *annexAry; //  维修图片  展示用
@property (nonatomic) NSMutableArray *annexDataAry; //  维修图片 提交用

@property (nonatomic) NSString *payEmployeeId; // 负责人id
@property (nonatomic) FuZeRenModel *fuZeModel; //  负责人模型
/**结清状态  0 未退请  1已退清*/
@property (nonatomic) NSInteger settleState;

@end

@implementation LXDepositApplyViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self layoutCustomNav:self.view title:@"退押金"];
   
     
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSDictionary *dic = @{
        @"url":@"upLoad_B",
    };
    self.annexAry = [NSMutableArray array];
    self.annexDataAry = [NSMutableArray array];

    
    
    [self.annexAry addObject:dic];
    
    [self.tableView registerClass:[LXTableViewCell class] forCellReuseIdentifier:NSStringFromClass([LXTableViewCell class])];
    [self.tableView registerClass:[LXApplyAnnexTableCell class]
         forCellReuseIdentifier:NSStringFromClass([LXApplyAnnexTableCell class])];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LXRemarkTabelViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([LXRemarkTabelViewCell class])];

    self.view.backgroundColor = White_Color;
    [self.view addSubview:self.tableView];
    
    [self loadData];
    
    [self setBottomViewWithText:@"确认"];
    
    
    
}
- (void)loadData{
    
    self.loanDic  = [NSMutableDictionary dictionary];
    
    
    // 模型为空,说明从车辆详情进入
//    if (!ObjectIsEmpty(self.depostiModel)) {
        
        self.carModel = [CheLiangModel new];
        self.carModel.ID = self.depostiModel.carId;
        self.carModel.carNum = self.depostiModel.carNumber;
        // 车牌号
        [self.loanDic setValue:self.depostiModel.carNumber forKey:@"carNum"];
        // 客户
    [self.loanDic setValue:!StringIsEmpty(self.depostiModel.customerName)?self.depostiModel.customerName:self.depostiModel.payeeName forKey:@"customerName"];
        // 应退日期
        [self.loanDic setValue:self.depostiModel.exceptPaidDate forKey:@"exceptPaidDate"];
        // 应退金额
        [self.loanDic setValue:self.depostiModel.amount forKey:@"amount"];
        // 应退金额
        [self.loanDic setValue:self.depostiModel.amount forKey:@"paidAmount"];
        // 退清状态
        self.settleState = 1;
        [self.loanDic setValue:@"已退清" forKey:@"settleState"];

//    }

    
    if (self.type== 2) {
        
        
        self.settleState = [self.depostiModel.settleState intValue];
        if (self.settleState==0) {
            [self.loanDic setValue:@"未退清" forKey:@"settleState"];
            
            
            [self.loanDic setValue:self.depostiModel.nextPayDate forKey:@"nextPayDate"];
            
            [self.loanDic setValue:self.depostiModel.nextPayAmount forKey:@"nextPayAmount"];
            
        }
        else {
            [self.loanDic setValue:@"已退清" forKey:@"settleState"];
        }
        
        
        
        [self.loanDic setValue:self.depostiModel.paidAmount forKey:@"Yamount"];
        
        [self.loanDic setValue:self.depostiModel.remark forKey:@"remark"];
        
        for (NSString *url in self.depostiModel.pics) {
            NSString *imageUrl = [NSString stringWithFormat:@"%@%@",HTTP_URL,url];
            [self.annexAry insertObject:@{@"url":imageUrl} atIndex:0];
            [self.annexDataAry insertObject:imageUrl atIndex:0];
        }
    
    }
      
    
    self.data = @[
         
           @{
               @"title":@"车牌号",
               @"key":@"carNum",
               @"placeHolder" : @"请选择车牌号",
               @"canEdit":@(NO),
               @"showAccess":@(NO),
               @"maxLength":@(1000),
               @"sel":@"",
               @"height":@(kComHeight)
           },
           @{
               @"title":@"客户",
               @"key":@"customerName",
               @"placeHolder" : @"-",
               @"canEdit":@(NO),
               @"showAccess":@(NO),
               @"maxLength":@(1000),
               @"sel":@"",
               @"height":@(kComHeight)
           },
           @{
               @"title":@"应退日期",
               @"key":@"exceptPaidDate",
               @"placeHolder" : @"--",
               @"canEdit":@(NO),
               @"showAccess":@(NO),
               @"maxLength":@(1000),
               @"sel":@"",
               @"height":@(kComHeight)
           },
           @{
               @"title":@"应退金额(元)",
               @"key":@"amount",
               @"placeHolder" : @"--",
               @"canEdit":@(NO),
               @"showAccess":@(NO),
               @"maxLength":@(10),
               @"sel":@"",
               @"height":@(kComHeight)
           },
           @{
               @"title":@"已退金额(元)",
               @"key":@"Yamount",
               @"height":[self.loanDic[@"Yamount"] doubleValue]>0?@(kComHeight):@(0.0001),
           },
           @{
               @"title":@"*实退日期",
               @"key":@"paidDate",
               @"placeHolder" : @"请选择实退日期",
               @"canEdit":@(NO),
               @"showAccess":@(YES),
               @"maxLength":@(1000),
               @"sel":@"clickReturnTime",
               @"height":@(kComHeight)
           },
           @{
               @"title":@"*实退金额(元)",
               @"key":@"paidAmount",
               @"placeHolder" : @"请输入实退金额",
               @"keyboardType":@(UIKeyboardTypeDecimalPad),
               @"canEdit":@(YES),
               @"showAccess":@(NO),
               @"maxLength":@(10),
               @"sel":@"",
               @"height":@(kComHeight)
           },
           @{
               @"title":@"*退押金状态",
               @"key":@"settleState",
               @"placeHolder" : @"请选择退押金状态",
               @"height":@(kComHeight),
               @"showAccess":@(YES),
               @"sel":@"clickReturnStatus",
           },
           @{
               @"title":@"*下次退押金日期",
               @"key":@"nextPayDate",
               @"placeHolder" : @"请选择下次退押金日期",
               @"canEdit":@(NO),
               @"showAccess":@(YES),
               @"maxLength":@(10),
               @"sel":@"clickNextPayDateAction",
               @"height":self.settleState==0?@(kComHeight):@(0.00001)
           }.mutableCopy,
           @{
               @"title":@"*下次退押金金额(元)",
               @"key":@"nextPayAmount",
               @"placeHolder" : @"请输入下次退押金金额",
               @"canEdit":@(YES),
               @"showAccess":@(NO),
               @"maxLength":@(8),
               @"inputType":@(NUM_DECIMAL),
               @"keyboardType":@(UIKeyboardTypeDecimalPad),
               @"sel":@"",
               @"height":self.settleState==0?@(kComHeight):@(0.00001)
           }.mutableCopy,
           @{
               @"title":@"付款人",
               @"key":@"payEmployeeName",
               @"placeHolder" : @"请选择付款人",
               @"height":@(kComHeight),
               @"showAccess":@(YES),
               @"sel":@"clickPayPerson",
           },
           @{
               @"title":@"附加图片(最多8张)",
               @"key":@"annex",
               @"height":@(kComAnnexHeight)
           },

           @{
               @"title":@"备注",
               @"key":@"remark",
               @"height":@(150)
           },
          
          
    ].mutableCopy;
  
    
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.data.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.data[indexPath.row];
    
    if ([dic[@"key"] isEqualToString:@"annex"]) {
        return [LXApplyAnnexTableCell getCellHeightWithDataSource:self.annexAry] + 30;
    }
    
    return [dic[@"height"] doubleValue];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSDictionary *dic = self.data[indexPath.row];

    // 维修图片
    if ([dic[@"key"] isEqualToString:@"annex"]) {
        LXApplyAnnexTableCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXApplyAnnexTableCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setClipsToBounds:YES];
        cell.titleLab.text = dic[@"title"];
        [cell reloadAnnexData:self.annexAry WithMaxNum:8];
        
        
        // 添加图片
        [cell setCallBackTakeAnnex:^(NSInteger num) {
            
            [[LXPhotoHelper shareHelper] showImageViewSelcteWithResultBlock:^(id data) {
                
                [self uploadImage:data];
                
            } andMultipleImageBlock:^(id data) {
                
                [self uploadImage:data];
                
            } andSelectedNum:8 - self.annexDataAry.count];
            
        }];
        
        
        // 放大图片
        [cell setCallBackExtendAnnex:^(NSInteger num,id obj) {
            LXBigImageView *view = [[LXBigImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) WithShowImageAry:self.annexDataAry];
            [view.scrollView setContentOffset:CGPointMake(ScreenWidth*num, 0) animated:NO];
            [[UIApplication sharedApplication].delegate.window addSubview:view];
            
        }];
        // 删除图片
        [cell setCallBackDeleteAnnex:^(NSInteger num) {
            
            [self.annexAry removeObjectAtIndex:num];
            [self.annexDataAry removeObjectAtIndex:num];

            [self.tableView reloadData];
        }];
        
        
        return cell;
    }
    // 备注
   else if([dic[@"key"]  isEqualToString:@"remark"]){
       LXRemarkTabelViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXRemarkTabelViewCell class])];
       cell.selectionStyle = UITableViewCellSelectionStyleNone;
       [cell setClipsToBounds:YES];
       cell.textView.placeholder = @"请输入 ~";
       cell.textView.maxLength = 200;
       cell.remarkTitle.text = dic[@"title"];
       cell.textView.text = self.loanDic[dic[@"key"]];
       [cell setTextViewEdit:^(NSString * _Nonnull textStr) {
           self.loanDic[dic[@"key"]]  = textStr;
       }];
       return cell;
   }
    
    LXTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXTableViewCell class])];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setClipsToBounds:YES];
    

    cell.cellDic = dic;
    cell.textFiled.hidden = NO;
    cell.subTitleLab.hidden = YES;
    cell.textFiled.text = self.loanDic[dic[@"key"]];
    

    cell.textfiledChangeBlock = ^(NSString * _Nonnull textStr) {
        self.loanDic[dic[@"key"]]  = textStr;
    };
    cell.textfiledDidChangeBlock = ^(NSString * _Nonnull textStr) {
        if ([dic[@"key"] isEqualToString:@"paidAmount"]) {
            
            if ([textStr doubleValue] == [self.depostiModel.amount doubleValue]) {
                self.settleState = 1;
                self.loanDic[@"settleState"] = @"已退清";
            }
            else {
                self.settleState = 0;
                self.loanDic[@"settleState"] = @"未退清";
            }
            
            [self nextPayHeight];
            
            [self.tableView reloadData];
            
        }
    };
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *dic = self.data[indexPath.row];
    self.selDic = dic;
    NSString * selName = dic[@"sel"];
    SEL action = NSSelectorFromString(selName);
    if ([self respondsToSelector:action]) {
        [self performSelector:action withObject:nil afterDelay:0];
    }

}

// MARK: 选择付款人
-(void)clickPayPerson{
    [self.view endEditing:YES];
    
    LXChooseManagerViewController *vc = [[LXChooseManagerViewController alloc] init];
    WEAKSELF
    [vc setToSendValue:^(FuZeRenModel * _Nonnull model) {
        [weakSelf.loanDic setValue:model.realName forKey:@"payEmployeeName"];
        weakSelf.payEmployeeId = model.ID;
        weakSelf.fuZeModel = model;
        [weakSelf.tableView reloadData];
    }];
    vc.model = self.fuZeModel;
    [self pushToNextController:vc];
}
//MARK: 退押金状态
-(void)clickReturnStatus{
    [self.view endEditing:YES];
    [Tool showSheetTitle:nil msg:nil cancelTitle:@"取消" oneBtnTitle:@"已退清" twoBtnTitle:@"未退清" cancelHandlerBlock:^{
    } oneHandlerBlock:^{
        self.settleState = 1;
        [self.loanDic setValue:@"已退清" forKey:@"settleState"];
        
        
        [self nextPayHeight];
        
        
        [self.tableView reloadData];
    } twoHandlerBlock:^{
        self.settleState = 0;
        [self.loanDic setValue:@"未退清" forKey:@"settleState"];
        
        [self nextPayHeight];
        
        
        [self.tableView reloadData];
    } onVC:self];
}
-(void)nextPayHeight{
    NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"key MATCHES[cd] %@", @"nextPayDate"];
    NSMutableDictionary *dic1 = [[self.data filteredArrayUsingPredicate:predicate1] firstObject];
    NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"key MATCHES[cd] %@", @"nextPayAmount"];
    NSMutableDictionary *dic2 = [[self.data filteredArrayUsingPredicate:predicate2] firstObject];
    if (self.settleState == 0) {
        
        [dic1 setValue:@(kComHeight) forKey:@"height"];
        [dic2 setValue:@(kComHeight) forKey:@"height"];
    }
    else{
        [dic1 setValue:@(0.0001) forKey:@"height"];
        [dic2 setValue:@(0.0001) forKey:@"height"];
    }
}
#pragma mark -- 选择实退日期
-(void)clickReturnTime{
    [self.view endEditing:YES];
    DatePickView *datePicker =[[DatePickView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withDateStr:self.loanDic[@"intoTime"] withIsMaxDate:YES withNoForward:NO WithTips:@"请选择实退日期"] ;
    [datePicker showBoomView];
    [[[UIApplication sharedApplication].delegate window] addSubview:datePicker];
    WEAKSELF
    datePicker.block = ^(NSString *yearString){
        [weakSelf.loanDic setObject:yearString forKey:weakSelf.selDic[@"key"]];
        [weakSelf.tableView reloadData];
    };
}
#pragma mark -- 下次退押金日期
-(void)clickNextPayDateAction{
    [self.view endEditing:YES];
    DatePickView *datePicker =[[DatePickView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withDateStr:self.loanDic[@"nextPayDate"] withIsMaxDate:YES withNoForward:NO WithTips:@"请选择下次退押金日期"] ;
    [datePicker showBoomView];
    [[[UIApplication sharedApplication].delegate window] addSubview:datePicker];
    WEAKSELF
    datePicker.block = ^(NSString *yearString){
        
        
        if([NSString compareDate:self.loanDic[@"paidDate"] withDate:yearString withFormat:k_DateFormat]==-1){
            showAlert(@"下次退押金日期不能小于本次退押金日期");
            return;
        }
        
        [weakSelf.loanDic setObject:yearString forKey:weakSelf.selDic[@"key"]];
        [weakSelf.tableView reloadData];
    };
}


- (NSMutableArray *)data{
    if (!_data) {
        _data = [[NSMutableArray alloc]init];
    }
    return _data;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, LL_StatusBarAndNavigationBarHeight, ScreenWidth, ScreenHeight - LL_StatusBarAndNavigationBarHeight - kComHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = White_Color;
        _tableView.contentInset = UIEdgeInsetsMake(0,0,kComHeight + 10,0);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}




#pragma mark ---- 确认新增/修改点击事件
- (void)clickBottomView:(UIButton *)sender{
    
   
    if (StringIsEmpty(self.loanDic[@"paidDate"])) {
        showAlert(@"请选择实退日期");
        return;
    }
    
    if (StringIsEmpty(self.loanDic[@"paidAmount"])) {
        showAlert(@"请输入实退金额");
        return;
    }
    
    if ([self.loanDic[@"paidAmount"] doubleValue] == 0) {
        showAlert(@"实退金额金额不能为0");
        return;
    }
    
    if (self.settleState == 0) {
        if (StringIsEmpty(self.loanDic[@"nextPayDate"])) {
            showAlert(@"请选择下次退押金日期");
            return;
        }
        if (StringIsEmpty(self.loanDic[@"nextPayAmount"])) {
            showAlert(@"请输入下次退押金金额");
            return;
        }
        if ([self.loanDic[@"nextPayDate"] doubleValue] == 0) {
            showAlert(@"下次退押金金额不能为0");
            return;
        }
    }
  
    
    
    [Tool showAlertTitle:@"是否确认提交" msg:nil cancelTitle:@"取消" commitBtnTitle:@"确定" cancelHandlerBlock:^{
    } commitHandlerBlock:^{
        
        
        NSMutableDictionary *dic = @{
            @"id":self.depostiModel.ID,
            @"carId":self.carModel.ID, // 所属车辆id
            @"carNum":self.carModel.carNum,// 所属车辆车牌号
            @"payEmployeeName":self.loanDic[@"payEmployeeName"],// 负责人
            @"payEmployeeId":self.payEmployeeId,// 负责人id
            @"settleState":@(self.settleState),//  结清状态
            @"paidDate":self.loanDic[@"paidDate"], //  实付日期
            @"paidAmount":self.loanDic[@"paidAmount"], //  实付金额
            @"remark":self.loanDic[@"remark"], //  备注
            @"pics":self.annexDataAry, //  图片
            
        }.mutableCopy;
        if (self.settleState == 0) {
            [dic setValue:self.loanDic[@"nextPayDate"] forKey:@"nextPayDate"];
            [dic setValue:self.loanDic[@"nextPayAmount"] forKey:@"nextPayAmount"];
        }
        
        [MSNetworkManager postRevertUrl:POST_DepositPay params:dic success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
            
            if (isSuccess) {
                showAlert(@"退押金成功");
                kUserDefaultSetBool(YES, kRefreshStr);
                
                [self.navigationController popViewControllerAnimated:YES];
            }
            
        } failure:^(NSUInteger code, NSString * _Nonnull message) {
        } withShowHud:YES];
    } onVC:self];
    
 
}

-(void)uploadImage:(NSArray *)ary{
    
    [self.annexAry removeLastObject];
    
    MBProgressHUD *hud = [MBProgressHUD showGif];
        
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        
    dispatch_async(queue, ^{
    
    [ary enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    
        [MSNetworkManager postRevertUrl:POST_UploadFile_URL params:@{@"type":@"1"} formData:@[obj] success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
            if (isSuccess) {
                NSString *imageUrl = [NSString stringWithFormat:@"%@%@",HTTP_URL,resonseObj[@"url"]];

                [self.annexAry addObject:@{
                    @"url":imageUrl
                }];
                [self.annexDataAry addObject:resonseObj[@"url"]];
            }
            if (idx == ary.count-1) {
                [hud hide];
                [self.annexAry addObject:@{
                    @"url":@"upLoad_B",
                }];
                [self.tableView reloadData];
            }
            dispatch_semaphore_signal(semaphore);
        } failure:^(NSUInteger code, NSString * _Nonnull message) {
            dispatch_semaphore_signal(semaphore);
            [hud hide];
        } withShowHud:NO];
        
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        
        
     }];
    });

}
@end
